package service.forkinjoin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.RecursiveAction;

import javax.mail.Message;
import javax.mail.MessagingException;

import service.EmailUtil;
import service.NullUtil;

public class ForkGetSenders extends RecursiveAction {

	private static final long serialVersionUID = -5391538981649222278L;
	private List<Message> listMessages;
	private Set<String> setSenders;

	public ForkGetSenders(List<Message> listMessages, Set<String> setSenders) {
		this.listMessages = listMessages;
		this.setSenders = setSenders;
	}

	@Override
	protected void compute() {

		List<RecursiveAction> actions = new ArrayList<>();

		if (this.listMessages.size() <= Runtime.getRuntime()
				.availableProcessors()) {
			try {
				this.getSenders();
			} catch (MessagingException | IOException e) {
				e.printStackTrace();
			}
		} else {

			int end = this.listMessages.size() / 2;
			actions.add(new ForkGetSenders(this.listMessages.subList(0, end), this.setSenders));
			end += this.listMessages.size() % 2 == 0 ? 0 : 1;
			actions.add(new ForkGetSenders(this.listMessages.subList(end, this.listMessages.size()), this.setSenders));
			invokeAll(actions);
		}
	}

	private void getSenders() throws MessagingException, IOException {

		for (Message message : this.listMessages) {
			
			if (!NullUtil.isNull(message)) {
				this.setSenders.add(EmailUtil.getSender(message));				
			}
		}
	}
}
